import React from 'react';
import MergeRequestGuide from './mergeRequestGuide';
import ReviewEstimateGuide from './reviewEstimateGuide';

export default class RobotGuides extends React.Component {
  constructor(props) {
    super(props);
    this.guides = [
      {
        assetsName: 'projectFiles',
        type: 'mergeRequestGuide',
      },
      {
        assetsName: 'projectMergeRequest',
        type: 'reviewEstimateGuide',
      },
    ];
  }

  state = {
    guideType: null,
  };

  componentDidMount() {
    this.changePopStatus(this.props.pageInfo.assetsName);
  }

  UNSAFE_componentWillReceiveProps(props) {
    const newAssetsName = props.pageInfo.assetsName;
    const oldAssetsName = this.props.pageInfo.assetsName;

    if (newAssetsName !== oldAssetsName) {
      this.changePopStatus(newAssetsName);
    }

    if (this.isHomePage(props.pageInfo)) {
      this.changePopStatus(props.pageInfo.assetsName);
    }
  }

  isHomePage(pageInfo) {
    const { pathname } = window.location;
    if (pageInfo.assetsName === 'organization' && pathname && !pathname.startsWith('/settings')) {
      return true;
    }
    return false;
  }

  getGuideInfoByPage(assetsName) {
    const { guides } = this;

    let guide = null;
    for (let i = 0; i < guides.length; i++) {
      if (guides[i].assetsName === assetsName) {
        guide = guides[i];
        break;
      }
    }
    return guide;
  }

  changePopStatus(assetsName) {
    const guide = this.getGuideInfoByPage(assetsName);

    if (!guide) {
      this.setState({
        guideType: null,
      });
    } else {
      this.setState({
        guideType: guide.type,
      });
    }
  }

  renderGuide(type) {
    if (type === 'mergeRequestGuide') {
      return <MergeRequestGuide />;
    } else if (type === 'reviewEstimateGuide') {
      return <ReviewEstimateGuide />;
    }
    return null;
  }

  render() {
    const { guideType } = this.state;
    if (!guideType) {
      return null;
    }

    return <div>{this.renderGuide(guideType)}</div>;
  }
}
